<?php


declare(strict_types=1);

namespace App\Repositories\Pet;


use App\Enums\PetEnum;
use App\Models\GameDB\Pet\Props;
use App\Traits\Singleton;

class PetPropsRepository
{
    use Singleton;


    public function getPropInfoByIds(array $propIds)
    {
        $giftInfos = Props::query()->whereIn('id', $propIds)->select('id', 'name', 'game', 'prope_icon', 'effective_icon')
            ->get()->toArray();
        $giftInfos = array_column($giftInfos, null, 'id');
        foreach ($giftInfos as &$item) {
            $item['game_name'] = PetEnum::PROPS_GAME_NAME[$item['game']] ?? '';
        }
        return $giftInfos;
    }

    public function addUserProps($userId, array $props)
    {
        $propsWithId = array_column($props, null, 'id');
        $propIds     = array_keys($propsWithId);
        $propList    = Props::query()->whereIn('id', $propIds)->select('id', 'effective_time', 'game')->get();
        $userPropLog = [];
        foreach ($propList as $prop) {
            $userPropLog [] = [
                "user_id"      => $userId,
                "props_id"     => $prop->id,
                "effective_at" => time() + $prop->effective_time * 24 * 3600,
                "props_num"    => $propsWithId[$prop->id]['count'],
                "un_used_num"  => $propsWithId[$prop->id]['count'],
            ];
        }
        app('model_user_props_log')->insert($userPropLog);
        return true;
    }

    public function batchAddUserProps(array $props)
    {
        $propIds        = array_column($props, 'id');
        $propList       = Props::query()->whereIn('id', $propIds)->select('id', 'effective_time', 'game')->get();
        $propListWithId = $propList->keyBy('id');
        $userPropLog    = [];
        foreach ($props as $prop) {
            $userPropLog [] = [
                "user_id"      => $prop['user_id'],
                "props_id"     => $prop['id'],
                "effective_at" => time() + $propListWithId[$prop['id']]['effective_time'] * 24 * 3600,
                "props_num"    => $prop['count'],
                "un_used_num"  => $prop['count'],
            ];
        }
        app('model_user_props_log')->insert($userPropLog);
        return true;
    }
}